package com.wangxiaotao.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentService {

    /**
     * 正常访问的方法
     * @param id
     * @return String
     */
    public String paymentInfo_Ok(Integer id){
        return "线程池："+Thread.currentThread().getName()+"paymentInfo_OK,id:"+id+"嘿嘿";
    }

    /**
     * 服务降级 超时配置3s
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties =
            {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")})
    public String paymentInfo_timeOut(Integer id){
        //int time=5;
        int i=10/0;
        //try { TimeUnit.SECONDS.sleep(time); }catch (Exception e){e.printStackTrace();}
        return "线程池："+Thread.currentThread().getName()+"paymentInfo_OK,id:"+id+"嘿嘿";
    }


    public String paymentInfo_TimeOutHandler(Integer id){
        return "线程池："+Thread.currentThread().getName()+":8001:超时啦，卧槽卧槽卧槽卧槽"+id;
    }

    //====服务熔断   ---->服务降级 熔断 再恢复
    @HystrixCommand(fallbackMethod ="paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name="circuitBreaker.enabled",value = "true"),//是否开启断路器
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "10"),//熔断触发最小请求次数，默认20
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//熔断后休眠时长
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "60")//失败率达到多少次跳匝 默认50%

    })
    public String paymentCircuitBreaker(Integer id){
        if(id<0){
            throw new RuntimeException("id不能为负数");
        }
        String serialNumber= IdUtil.simpleUUID();
        return Thread.currentThread().getName()+"\t"+"调用成功，流水号："+serialNumber;
    }

    public String paymentCircuitBreaker_fallback(Integer id){
        return  "id 不能为负数，请稍后再试  id："+id;
    }
}
